package com.attendance.utils;

import com.attendance.entity.TeamUser;
import com.attendance.entity.User;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.MessageFormat;

@Component
public class GenerateEmailContent {

    @Autowired
    private JavaMailSender sender;

    private final static SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

    public Boolean SendRegisterVerifyCodeEmail(String code, String toEmail) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setSubject("【小佘佘\uD83E\uDD80】您正在登录Attendance应用，您的验证码是：" + code + "，转发给他人可能导致账号被盗，请勿泄漏，谨防被骗。");
            mimeMessageHelper.setText(buildHTMLContentByCodeEmail(code, toEmail), true);
            mimeMessageHelper.setFrom(new InternetAddress(MimeUtility.encodeText("Attendance") + "<redjanji@qq.com>").toString());
            mimeMessageHelper.setTo(toEmail);
            sender.send(mimeMessage);
        } catch (MessagingException | UnsupportedEncodingException e) {
            return false;
        }
        return true;
//        =====================================
//        try {
//            simpleMailMessage.setFrom(new InternetAddress(MimeUtility.encodeText("Attendance") + "<redjanji@qq.com>").toString());
//            simpleMailMessage.setSubject("Attendance");
//            simpleMailMessage.setText("【小佘佘🦀】您正在注册Attendance应用，您的验证码是：" + code + "\n转发给他人可能导致账号被盗，请勿泄漏，谨防被骗。");
//            simpleMailMessage.setTo(toEmail);
//            sender.send(simpleMailMessage);
//        } catch (AddressException | UnsupportedEncodingException e) {
//            return false;
//        }
//        return true;
    }

    public Boolean SendInviteTeamEmail(TeamUser teamUser, String toEmail) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setSubject("【小佘佘\uD83E\uDD80】 你收到一份团队邀请函，请接收！");
            mimeMessageHelper.setText(buildHTMLContentByInviteEmail(teamUser), true);
            mimeMessageHelper.setFrom(new InternetAddress(MimeUtility.encodeText("Attendance") + "<redjanji@qq.com>").toString());
            mimeMessageHelper.setTo(toEmail);
            sender.send(mimeMessage);
        } catch (MessagingException | UnsupportedEncodingException e) {
            return false;
        }
        return true;
    }

    public Boolean SendApplyTeamEmail(Integer teamId, Integer userId, User user) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setSubject("【小佘佘\uD83E\uDD80】 你收到一份入团申请，请接收！");
            mimeMessageHelper.setText(buildHTMLContentByApplyTeamEmail(teamId, userId, user), true);
            mimeMessageHelper.setFrom(new InternetAddress(MimeUtility.encodeText("Attendance") + "<redjanji@qq.com>").toString());
            mimeMessageHelper.setTo(user.getEmail());
            sender.send(mimeMessage);
        } catch (MessagingException | UnsupportedEncodingException e) {
            return false;
        }
        return true;
    }

    public String buildHTMLContentByApplyTeamEmail(Integer teamId, Integer userId, User user) {
        ClassPathResource resource = new ClassPathResource("templates/email/email_apply.ftl");
        InputStream inputStream = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return MessageFormat.format(buffer.toString(), teamId, userId, user.getUsername());
    }

    public String buildHTMLContentByInviteEmail(TeamUser teamUser) {
        ClassPathResource resource = new ClassPathResource("templates/email/email_invite.ftl");
        InputStream inputStream = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return MessageFormat.format(buffer.toString(), teamUser.getU_id(), teamUser.getT_id(), teamUser.getName());
    }

    public String buildHTMLContentByCodeEmail(String code, String toEmail) {
        ClassPathResource resource = new ClassPathResource("templates/email/email_code.ftl");
        InputStream inputStream = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return MessageFormat.format(buffer.toString(), code);
    }
}
